package com.handinfo.engine.resource;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.handinfo.util.Tools;

/**
 * @author Xia Mingwei
 * @version 1.0
 */
public abstract class Serializeable
{
	// 资源头
	public ResHead m_resHead;
	// 依赖资源的资源头
	public ResHead[] m_refsResHead;
	// 对应的Resource容器
	public Resource m_resource;
 
	//

	/**
	 * 读取文件头信息
	 * 
	 * @param res
	 * @param dis
	 * @throws IOException
	 */
	protected void readHeader(Resource res, DataInputStream dis) throws IOException
	{
		m_resource = res;
		int length = dis.readShort();
		m_refsResHead = new ResHead[length];
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < length; i++) {
			m_refsResHead[i] = new ResHead();
			m_refsResHead[i].m_type = dis.readByte();
			String url = dis.readUTF();
			m_refsResHead[i].m_version = dis.readInt();
			buffer.delete(0, buffer.length());
			switch(m_refsResHead[i].m_type) {
				case ObjectAdapter.RESOURCE_TYPE_ANIM:
					buffer.append(ObjectAdapter.DIR_ANIM);
					buffer.append(url);
					buffer.append(ObjectAdapter.EXTENSION_ANIM);
					break;
				case ObjectAdapter.RESOURCE_TYPE_BG:
					buffer.append(ObjectAdapter.DIR_BG);
					buffer.append(url);
					buffer.append(ObjectAdapter.EXTENSION_BG);
					break;
				case ObjectAdapter.RESOURCE_TYPE_PNG:
					buffer.append(ObjectAdapter.DIR_IMG);
					buffer.append(url);
					buffer.append(ObjectAdapter.EXTENSION_IMG);
					break;
				case ObjectAdapter.RESOURCE_TYPE_SCENE:
					buffer.append(ObjectAdapter.DIR_SCENE);
					buffer.append(url);
					buffer.append(ObjectAdapter.EXTENSION_SCENE);
					break;
			}
			m_refsResHead[i].m_url = buffer.toString();
		}
	}

	public boolean isContainHeader(ResHead head)
	{
		if (m_refsResHead == null || m_refsResHead.length == 0)
			return false;
		for (int i = 0; i < m_refsResHead.length; i++) {
			if (m_refsResHead[i] != null && m_refsResHead[i].equals(head)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 销毁头信息
	 */
	protected void disposeHeader()
	{
		if (m_refsResHead != null) {
			for (int i = 0; i < m_refsResHead.length; i++) {
				m_refsResHead[i] = null;
			}
			m_refsResHead = null;
		}
	}

	public abstract void read(Resource res, DataInputStream dis)throws IOException ;
	
	/**
	 * 载入
	 * 
	 * @param res
	 * Resource
	 * @param dis
	 * DataInputStream
	 */
//	public void read(Resource res, InputStream is)
//			throws IOException {
//		
//	}

	/**
	 * 更新属性对象:用于动态加载
	 * 
	 * @param type
	 * byte
	 * @param url
	 * String
	 * @param compose
	 * Serializeable
	 */
	public abstract void updateComponent(ResHead head, Serializeable component);

	public boolean m_loadFinished;

	/**
	 * 检查该对象是否全部载入
	 */
	public abstract void checkLoadFinished();

	/**
	 * 销毁对象
	 */
	public abstract void dispose();
}
